import React, {useEffect, useRef, useState} from 'react'
import {Button, Input, InputNumber, Modal} from 'antd'
import './index.less'
import {loadAMap} from '@/utils/aMap'
import useBaseFontSize from "@/hooks/useBaseFontSize.ts";
import AppConfig from "@/config";

const formatValue = (value) => {
  const {lng, lat} = value || {}
  if ((lng || lng === 0) && (lat || lat === 0)) {
    return `${lng},${lat}`
  } else {
    return ''
  }
}

function LngLatChoose(props) {
  const mapConfig = AppConfig.map;

  const [lnglat, setLngLat] = useState()
  const [value, setValue] = useState(lnglat)
  const [visible, setVisible] = useState(false)
  const [marker, setMarker] = useState(null)
  const [map, setMap] = useState(null)
  const mapCache = useRef(null)

  const closeEditReport = () => {
    setVisible(false)
    setLngLat()
  }
  const clearMarker = () => {
    setLngLat()
  }
  const drawMarker = () => {
    if (!marker) return false
    if (!map) return false
    if (!lnglat) {
      marker.setMap(null)
      return false
    }
    try {
      marker.setPosition([lnglat.lng, lnglat.lat])
      map.panTo([lnglat.lng, lnglat.lat])
      marker.setMap(map)
    } catch (error) {
      console.log("error", error)
    }
  }
  const mapClick = (e) => {
    setLngLat(e.lnglat)
  }
  const chooseLngLat = () => {
    props.onChange(lnglat)
    setValue(lnglat)
    closeEditReport()
  }
  useEffect(() => {
    drawMarker()
  }, [lnglat, marker])
  useEffect(() => {
    if (props.value) {
      setValue(props.value)
    }
  }, [props.value])
  useEffect(() => {
    if (!map) {
      return
    }
    map.on('click', mapClick)
    setMarker(
      new window.AMap.Marker({
        content: "<div class='map-icon'></div>",
        offset: new window.AMap.Pixel(-13, -30),
      }),
    )
    const auto = new window.AMap.AutoComplete({
      input: 'tipinput',
    })
    const select = (e) => {
      if (e.poi.location) {
        setLngLat(e.poi.location)
      } else if (e.poi.adcode) {
        map.setCity(e.poi.adcode)
      }
    }
    window.AMap.Event.addListener(auto, 'select', select) //注册监听，当选中某条记录时会触发
  }, [map])
  useEffect(() => {
    if (!visible) {
      return
    }
    mapCache.current
      .then((AMap) => {
        setMap(new AMap.Map('map-container', {
          center: mapConfig.center,
          zoom: mapConfig.zoom
        }))
      })
      .catch((e) => {
        console.log(e)
      })
    value && setLngLat(value)
  }, [visible])

  useEffect(() => {
    mapCache.current = new Promise((resolve) => {
      loadAMap().then((AMap) => {
        window.AMap.plugin(['AMap.AutoComplete', 'AMap.PlaceSearch'], function () {
          resolve(AMap)
        })
      })
    })
  }, [])

  const handleInputChange = (e) => {
    setLngLat(e.target.value)
  }

  const baseFontSize = useBaseFontSize();

  return (
    <>
      {props.disabled ? (
        value ? (
          formatValue(value)
        ) : (
          '-'
        )
      ) : (
        <Button
          style={{padding: 0}}
          type="link"
          onClick={() => {
            setVisible(true)
          }}
        >
          {value ? formatValue(value) : '点击选择'}
        </Button>
      )}
      <Modal
        title="选择位置"
        open={visible}
        onCancel={closeEditReport}
        getContainer={false}
        width={baseFontSize * 700}
        centered={true}
        bodyStyle={{padding: 0}}
        className="map-module"
        footer={[
          <Button key="close" onClick={closeEditReport}>
            关闭
          </Button>,
          <Button key="cancel" onClick={clearMarker}>
            清除
          </Button>,
          <Button type="primary" key="submit" onClick={chooseLngLat}>
            确认选择
          </Button>,
        ]}
      >
        <div id="map-container"></div>
        <div className="map-lnglat-text">
          <div className="latlng-input" style={{marginBottom: 12}}>
            <span className="latlng-input-title">经度：</span>
            <InputNumber
              style={{width: 130 * baseFontSize}}
              value={lnglat?.lng}
              controls={false}
              onChange={(value) => setLngLat((v) => ({...v, lng: value}))}
            />
          </div>
          <div className="latlng-input">
            <span className="latlng-input-title">纬度：</span>
            <InputNumber
              style={{width: 130 * baseFontSize}}
              value={lnglat?.lat}
              controls={false}
              onChange={(value) => setLngLat((v) => ({...v, lat: value}))}
            />
          </div>
        </div>
        <div className="map-lnglat-input">
          <input id="tipinput"/>
        </div>
      </Modal>
    </>
  )
}

export default LngLatChoose
